<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    //订阅者都有自己的update方法用于更新信息；发布者负责调用所有订阅者的update方法

    //发布者 - 目标
    class Dep {
        constructor () {
            this.subs = []  //记录所有订阅者
        }
        addSub (sub) {
            if( sub && sub.update ) {
                this.subs.push(sub)
            }
        }
        notify (data) {
            this.subs.forEach(sub=>{
                sub.update(data)
            })
        }
    }

    //订阅者 - 观察者

    class Watcher {
        update(msg) {
            console.log(msg)
        }
    }

    const dep = new Dep()
    const watcher = new Watcher()

    dep.addSub( watcher )
    dep.notify('公告更新了')
</script>
</html>